<script setup>
import {computed, inject, reactive, watch, defineEmits, ref} from "vue";
import 'jiuqi-ui'
import {getTreeNodeByGuid,getAllParentNode} from "../../../utils/TreeHelper";
import {useDialog} from "jiuqi-ui";

//================================================【公用相关】============================================================
//请求工具
const context = inject('context')
//提示框
const dialogPop = useDialog()
//表格表头信息
const  tablecolumns = reactive([])
//表格数据
const tableData = reactive([])
//树形数据
const treeData = reactive([])
//================================================【组件通信】============================================================
//获取当前模型ID
const {currAbcModelGuid} = inject('abcmodel')
//控制  取数公式选择模态框  显示和隐藏
const formulaItemSelectorVisible = inject('formulaItemSelectorVisible')
//控制  取数公式入口模态框  显示 和 隐藏
const genFormulaVisible = inject('genFormulaVisible')
//获取父组件参数
const props = defineProps({
    selectType: String
});
//当前选择的表名
const currentParameter = inject('currentParameter')

const emits = defineEmits(['selfCloseParentVisable']);
//================================================【组件属性】============================================================
//模态框标题
const modalTitle = computed(()=>{
    switch (props.selectType) {
        case 'tableName':
            return '选择取数明细表';
        case 'memberCode':
            return '选择取数维度';
        case 'quotaName':
            return '选择取数字段';
        default:
            return '';
    }
})
//监听取数公式选择模态框 显示与否
watch(formulaItemSelectorVisible, (newValue) => {
    if (newValue){
        initDataTableTree()
        initFieldTableTable()
    }
    // console.log('触发侦听事件',newValue+oldValue)
})
//================================================【普通方法】============================================================
//==================================================================【树形相关】
const formulaItemTree = ref(null)
/**
 * 初始化树形  获取树形根节点
 */
function initDataTableTree() {

    if (currentParameter.tableName === ''){
        //获取 取数表 根节点
        context.getPlugin('http').get(`abc/model/resourceMember/generateFormula/dataTableList/${currAbcModelGuid.value}/null`)
            .then((res) =>{
                //获取根节点
                treeData.splice(0,treeData.length,...res.data.rootNodeArr)
                treeData[0].expand = true
                //获取二级节点
                treeData[0].children = res.data.tableList
            })

    //树形回显
    } else {
        const selectedNode = getTreeNodeByGuid(treeData,currentParameter.tableName)
        //情景1：选择节点B 后 点击节点B的 父节点（节点A）,此时节点节点B被折叠，下次进来时需要根据 节点B 追溯路径进行逐级展开
        const retrospectArr = getAllParentNode(treeData,selectedNode)
        while (retrospectArr.length > 0) {
            const processNode = retrospectArr.pop();
            processNode.expand = true
        }
        selectedNode.selected = true
        setTimeout(function () {
            let dom = document.querySelector("#treeitem" + currentParameter.tableName);
            if (dom) {
                dom.scrollIntoView({
                    //滚动到指定节点
                    block: 'center', //值有start,center,end，nearest，当前显示在视图区域中间
                    behavior: 'smooth' //值有auto、instant,smooth，缓动动画（当前是慢速的）
                })
            }
        }, 300)
    }
}

/**
 * 异步加载树形
 * @param item 点击树形节点
 * @returns {Promise<unknown>} 异步处理
 */
function loadData(item) {
    //如果节点已经展开则不做处理
    if (item.expand) {
        return
    }

    //节点未展开时处理
    return new Promise((resolve) => {
        context.getPlugin('http').get(`abc/model/resourceMember/generateFormula/dataTableList/${currAbcModelGuid.value}/${item.id}`).then((res) => {
            let subNodeList = res.data.tableList
            const nodeDataArr = []
            if (subNodeList.length === 0) {
                item.expand = true
            }
            for (let i = 0; i < subNodeList.length; i++) {
                const nodeData = subNodeList[i];

                if (!nodeData.leaf) {
                    nodeData.expand = false
                } else {
                    nodeData.expand = true
                }
                nodeDataArr.push(nodeData)
            }
            resolve(nodeDataArr)
        })
    })
}

//点击获取树形数据
function treeNodeClick(node) {
    // console.log(node)
    if (node !== null) {
        currentParameter.tableName = node.id
    }
}

//==================================================================【表格相关】
/**
 * 初始化表格 根据获取到的表名（tableName）查询表中字段信息
 */
function initFieldTableTable() {
    //初始化数据
    tablecolumns.length = 0;

    //成本指标，成本池编码指标
    tablecolumns.push(
        {
            title: '序号',
            key: 'order',
            width:50
        },
        {
            title: '名称',
            key: 'title',
            width:145
        },
        {
            title: '标识',
            key: 'name',
            width:145
        },
        {
            title: '数据类型',
            key: 'dataTypeTitle',
            width:145
        })

    if (currentParameter.tableName !== '') {
        //获取 取数表字段
        context.getPlugin('http').get(`abc/model/resourceMember/generateFormula/tableField/${currentParameter.tableName}`)
            .then((res) =>{
                if (props.selectType === 'quotaName') {
                    processTableValue(res.data.zbList,'quotaName')
                }
                if (props.selectType === 'memberCode') {
                    processTableValue(res.data.wdList,'memberCode')
                }

            })
    }

}
//点击获取表格数据
function tableLineClick(curLineItem) {
  //表格只允许同一时间显示一条高亮行
  tableData
      .filter(preFilterItem => {
        return preFilterItem.name !== curLineItem.name
      })
      .map(preMapItem => preMapItem.highlight = false)

  if (curLineItem.highlight) {
    if (props.selectType === 'memberCode')
      currentParameter.memberCode = curLineItem.name
    else if (props.selectType === 'quotaName')
      currentParameter.quotaName = curLineItem.name
  }else {
    if (props.selectType === 'memberCode')
      currentParameter.memberCode = ''
    else if (props.selectType === 'quotaName')
      currentParameter.quotaName = ''
  }
}

//==================================================================【确认选择】
//确认按钮加载状态
const confirmLoading = ref(false)

function selectorConfirm() {
    if (confirmLoading.value) {
        return
    }
    //开始加载状态
    confirmLoading.value = true

    //校验当前待返回数据是否为空
    let warningInfo = ''
    if (props.selectType === 'tableName' && currentParameter.tableName === '')
        warningInfo = '未选择取数表'
    if (props.selectType === 'memberCode' && currentParameter.memberCode === '')
        warningInfo = '未选择取数维度'
    if (props.selectType === 'quotaName' && currentParameter.quotaName === '')
        warningInfo = '未选择取数字段'

    if (warningInfo !== '') {
      dialogPop.warning({
        title: '提示',
        content: `${warningInfo}`
      })
    }else {
      //还原表格数据
      tableData.splice(0, tableData.length)

      //子 隐 父 显
      emits('selfCloseParentVisable');
    }
    //结束加载状态
    confirmLoading.value = false
}

//==================================================================【取消选择】
function selectorCancel() {
    //还原数据
    tableData.splice(0,tableData.length)

    //取消选择后，选择状态的树形节点应该还原。
    if (formulaItemTree.value) {
        const selectedNode = formulaItemTree.value.getSelectedNodes()[0];
        if (selectedNode) {
            selectedNode.selected = false;
        }
    }

    //子 隐 父 显
    emits('selfCloseParentVisable');
}
//==================================================================【关闭选择模态框】
function getVisibleChange(info) {
    //当 取数公式选择模态框 关闭时
    if (info === false) {
        //取数公式入口模态框 需要保持显示
        genFormulaVisible.value = true
    }
}
//==================================================================【处理 表字段信息  生成 表格展示信息】
function processTableValue(fieldList, type) {

    for (let i = 0; i < fieldList.length; i++) {
        fieldList[i].order = i + 1;
        fieldList[i].highlight = false
        if (type === 'quotaName'
            &&
            currentParameter.quotaName
            &&
            currentParameter.quotaName === fieldList[i].name) {
            fieldList[i].highlight = true
        }


        if (type === 'memberCode'
            &&
            currentParameter.memberCode
            &&
            currentParameter.memberCode === fieldList[i].name) {
            fieldList[i].highlight = true
        }
    }
    tableData.splice(0, tableData.length, ...fieldList)
}
</script>

<template>
    <j-modal
            v-model="formulaItemSelectorVisible"
            :title="modalTitle"
            :fullscreenable='false'
            :mask="false"
            :mask-closable="false"
            :closable="!confirmLoading"
            @visible-change="getVisibleChange"
    >
        <j-modal-content size="small" style="height: 223px">
           <div v-if="selectType === 'tableName'">
               <j-tree  ref="formulaItemTree"
                        v-model:data="treeData"
                        :load-data="loadData"
                        @select="treeNodeClick"
                        select-type="check"
               >
                   <template #node="{ title,id,isLeaf }">
                         <span :id="'treeitem' + id" style="width:100%;">
                            <j-space :size="8">
                                <div v-if="isLeaf">
                                    <span class=" nvwa-iconfont icon14_SHU_A_NW_tubiaozhongji"></span>
                                </div>
                                <div v-else>
                                   <span class=" nvwa-iconfont icon14_SHU_A_NW_tubiaokezhankai"></span>
                                </div>
                              <span>{{ title }}</span>
                            </j-space>
                         </span>
                   </template>
               </j-tree>
           </div>
            <div v-if="selectType === 'quotaName' || selectType === 'memberCode'">
                <j-Table  :columns="tablecolumns"
                          :data="tableData"
                          @row-click="tableLineClick"
                          highlight
                          border
                ></j-table>
            </div>
        </j-modal-content>
        <template #footer>
           <j-space style="justify-content: flex-end">
               <j-button @click="selectorCancel" :disabled="confirmLoading">取消</j-button>
               <j-button type="primary" :loading="confirmLoading" @click="selectorConfirm">确定</j-button>
           </j-space>
        </template>
    </j-modal>
</template>

<style scoped>
</style>
